//
//  DraggingView.swift
//  ImageColorPicker
//
//  Created by tanwz on 16/6/1.
//  Copyright © 2016年 tanwz. All rights reserved.
//

import Cocoa

@objc protocol DraggingViewDelegate {
    optional func DragedFiles(files: Array<NSString>)
    optional func MouseMoved(pos: CGPoint)
    optional func MouseDown(pos: CGPoint)
}

class DraggingView: NSView {
    
    var delegate: DraggingViewDelegate?
    
    override func awakeFromNib() {
        registerForDraggedTypes([NSFilenamesPboardType])
        
        window?.makeFirstResponder(self)
        window?.acceptsMouseMovedEvents = true
    }
    
    deinit {
        unregisterDraggedTypes()
    }
    
    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        // Drawing code here.
    }
    
    override func acceptsFirstMouse(theEvent: NSEvent?) -> Bool {
        return true
    }
    
    override func updateTrackingAreas() {
        super.updateTrackingAreas()
        
        let trackings = trackingAreas
        for tracking in trackings {
            removeTrackingArea(tracking)
        }
        
        let options = NSTrackingAreaOptions(rawValue: NSTrackingAreaOptions.ActiveAlways.rawValue
            | NSTrackingAreaOptions.MouseEnteredAndExited.rawValue
            | NSTrackingAreaOptions.MouseMoved.rawValue
            | NSTrackingAreaOptions.CursorUpdate.rawValue)
        let trackingArea = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
        addTrackingArea(trackingArea)
        
//        Swift.print(#function)
    }
    
    override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
        return NSDragOperation.Copy
    }
    
    override func prepareForDragOperation(sender: NSDraggingInfo) -> Bool {
        let files = sender.draggingPasteboard().propertyListForType(NSFilenamesPboardType)
        
        Swift.print(files)
        
        if let draggedFiles = delegate?.DragedFiles {
            draggedFiles(files as! Array<NSString>)
        }
        
        return true;
    }
    
    override func draggingEnded(sender: NSDraggingInfo?) {
//        Swift.print(#function)
    }
    
    override func mouseDown(theEvent: NSEvent) {
//        Swift.print(#function)
        if let down = delegate?.MouseDown {
            down(theEvent.locationInWindow)
        }
    }
    
    override func mouseUp(theEvent: NSEvent) {
//        Swift.print(#function)
    }
    
    override func mouseMoved(theEvent: NSEvent) {
        if let move = delegate?.MouseMoved {
            move(theEvent.locationInWindow)
        }
    }
}
